// 管理用户数据相关
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getUser } from '@/apis/getUser'
import { useCarStore } from './useCarStore'
import { mergeCart } from '@/apis/getCart'

export const useUserStore = defineStore(
  'user',
  () => {
    const userStore = ref({})
    const carStore = useCarStore()
    const getUserInfo = async ({ account, password }) => {
      const res = await getUser({ account, password })
      userStore.value = res.result
      await mergeCart(
        carStore.carList.map((item) => {
          return {
            skuId: item.skuId,
            selected: item.selected,
            count: item.count,
          }
        })
      )
      carStore.updateCar()
    }
    const getClearUser = () => {
      userStore.value = {}
      carStore.clearCar()
    }
    // 3. 以对象的格式把state和action return
    return {
      userStore,
      getUserInfo,
      getClearUser,
    }
  },
  {
    persist: true,
  }
)
